package stack;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.Queue;

public class decodeString {
    Deque<String> queue = new ArrayDeque<>();

    public String decodeString(String s) {
        // 存放每一对数字和字母序列的位数
        // Deque<Integer> queue1 = new ArrayDeque<>();
        // 存放数字
        int i = 0;
        while (i < s.length()) {
            // ArrayList<Integer> numlist = new ArrayList<>();
            if (Character.isDigit(s.charAt(i))) {
                StringBuffer numlist = new StringBuffer();

                while (Character.isDigit(s.charAt(i))) {
                    numlist.append(s.charAt(i));
                    i++;
                }
                // 转换成数字
                // int sum = 0;
                // for (int j = 0; j < numlist.size(); j++) {
                // sum += numlist.get(i) * Math.pow(10, numlist.size() - 1-j);
                // }
                queue.push(numlist.toString());
            }
            if (s.charAt(i) == '[') {
                queue.push("[");
                i++;
            } else if (Character.isLetter(s.charAt(i))) {
                StringBuffer charlist = new StringBuffer();
                while (i < s.length()&& Character.isLetter(s.charAt(i)) ) {
                    charlist.append(s.charAt(i));
                    i++;

                }
                queue.push(charlist.toString());
            } else {
                // 一直出到【
                // 要循环，不能单独pop
                ArrayList<String> wordlist = new ArrayList<>();
                while (queue.peek() != "[") {
                    String word = queue.pop();
                    wordlist.add(word);
                }
                queue.pop();
                String num = queue.pop();
                StringBuffer temp = new StringBuffer();
                Collections.reverse(wordlist);
                for (String word : wordlist) {
                    temp.append(word);
                }
                String copy = temp.toString();
                for (int j = 0; j < Integer.parseInt(num) - 1; j++) {
                    temp.append(copy);
                }
                queue.push(temp.toString());
                i++;
            }

        }
        // 将stack中的颠倒
        Deque<String> reverse = new ArrayDeque<>();
        while (queue.peek() != null) {
            reverse.push(queue.pop());
        }
        StringBuffer result = new StringBuffer();
        while (reverse.peek() != null) {
            result.append(reverse.pop());
        }
        return result.toString();
    }

    public static void main(String[] args) {
        // String string = "3[a]2[bc]";
        // String string = "3[a2[c]]";
        // String string = "2[abc]3[cd]ef";
        String string = "abc3[cd]xyz";
        decodeString obj = new decodeString();
        System.out.println(obj.decodeString(string));
    }
}
